<template>
    <div>
        <el-dialog
            width="500px"
            :title="form.id ? '编辑品牌顾问' : '新增品牌顾问'"
            :visible.sync="visible"
            :before-close="handleClose"
            custom-class="adviser-dialog">
            <el-form :model="form" ref="form" id="form" size="small" :rules="rules">
                <el-form-item label="品牌" prop="brand1_id">
                    <el-select v-model="form.brand1_id" placeholder="选择品牌" @change="val => handleBrand(false, val, 0)">
                      <el-option v-for="(item, index) in brandArr" :key="index" :label="item.brand_initial+ ' ' + item.brand_name" :value="item.brand_id"></el-option>
                    </el-select>
                </el-form-item>
                <!--el-form-item label="品牌" prop="brand2_id">
                    <el-select v-model="form.brand2_id" placeholder="选择品牌" @change="val => handleBrand(false, val, 1)">
                      <el-option v-for="(item, index) in getCarBrandOptions(form.brand1_id)" :key="index" :label="item.brand_name" :value="item.brand_id"></el-option>
                    </el-select>
                </el-form-item-->
                <el-form-item label="品牌名称" prop="sort"> 
                    <el-input type="text" autocomplete="off" v-model="form.brand2_name" maxlength="30"></el-input>
                </el-form-item>
                <el-form-item label="店铺ID" prop="store_id">
                    <el-input
                        v-model="form.store_id"
                        @click.native="showStoreBox = true"
                        maxlength="8"
                        readonly>
                    </el-input>
                </el-form-item>
                <el-form-item label="排序优先级" prop="sort"> 
                    <el-input type="text" autocomplete="off" v-model.number="form.sort" maxlength="5" @input="handleNumber('sort')"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button size="small" @click="handleClose">取 消</el-button>
                <el-button size="small"
                    type="primary"
                    @click="submitForm('form')">
                    确 定
                </el-button>
            </template>
            <store-list :showStoreBox.sync="showStoreBox" @chooseStore="getStoreInfo"></store-list>
        </el-dialog>
    </div>
</template>
<script>
import storeList from "@/components/home/store-list.vue"
import {adviser, adviserSave} from './urlApi'
export default {
    props: ['options', 'getData'],     // 接收父组件传值
    components: { storeList },
    data() {
        return {
            formDefault: {
                id: '',
                brand1_id: null,
                brand1_name: '',
                brand2_id: null,
                brand2_name: '',
                brand_icon: '',
                store_name: '',
                store_id: '',
                sort: ""
            },
            visible: false,
            form: {},
            brandArr: [], // 品牌分类,
            selectedBrand: [],
			showStoreBox: false,
            rules: {
                brand1_id: [
                    { required: true, message: '请选择品牌', trigger: 'change' }
                ],
                /*
                brand2_id: [
                    { required: true, message: '请选择品牌', trigger: 'change' }
                ],*/
                brand2_name: [
                    { required: true, message: '请输入品牌名称', trigger: 'blur' }
                ],
                store_id: [
                    { required: true, message: '请选择店铺ID', trigger: 'change' }
                ],
                sort: [
                    { required: true, message: '请输入排序优先级', trigger: 'blur' }
                ]
            },
        }
    },
    computed: {
      getCarBrandOptions() {
        return function(brand_id) {
          if(!brand_id) return
          const brand = this.brandArr.find(item => item.brand_id == brand_id)
          return brand && brand.details || []
        }
      }
    },
    methods: {
        handleClose(reset = false) {
            reset && this.$refs.form.resetFields();
            this.visible = false
        },
        showStoreList(from, row) {
            this.showStoreBox = true;
            this.storeFrom = from;
            this.storeIdItem = row;
        },
        getStoreInfo(store) {
            switch (this.storeFrom) {
                case 'plantForm':
                    this.storeIdItem.storeid = store.storeName;
                    this.storeIdItem.redeem_businessId = store.storeId;
                    break;
                default:
                    this.form.store_name = store.storeName;
                    this.form.store_id = store.storeId;
            }
        },
        // 品牌
        handleBrand(init = false, val, index = 0) {
            if (init) {
                if (!val) {
                    adviser.getBrand({fid: 1}).
                    then(res => {
                        this.brandArr = res || [];
                    })
                } else {
                    adviser.getBrand({fid: val}).
                    then(res => {
                        for (let [index, value] of this.brandArr.entries()) {
                            if (value.brand_id == val) {
                                this.$set(this.brandArr[index], "details", res || [])
                                this.selectedBrand = this.brandArr[index]
                                return
                            }
                        }
                    })
                }
            } else {
                // 一级厂商
                if (index == 0) {
                    let _index = 0
                    this.selectedBrand = this.brandArr.find((item, key) => {
                        if(item.brand_id == val) {
                            _index = key
                            return item
                        }
                    })
                    this.form.brand1_name = this.selectedBrand.brand_name
                    this.form.brand_icon = this.selectedBrand.brand_icon
                    this.$set(this.form, "brand2_id", "")
                    this.$set(this.form, "brand2_name", "")
                    if(!this.selectedBrand.details) {
                        adviser.getBrand({fid: this.selectedBrand.brand_id}).
                        then(res => {
                          this.$set(this.brandArr[_index], 'details', res)
                        })
                    }
                } else if (index == 1) {
                    const brand2 = this.selectedBrand.details.find(item => item.brand_id == val)
                    this.form.brand2_name = brand2.brand_name
                }
            }
        },
        handleNumber(val) {
            this.form[val] = this.form[val].toString().replace(/[^\d]/g, '')
        },
        submitForm(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    if (this.form.id) {
                        adviserSave.update(this.form).then(res => {
                            if(res.code == 1) {
                                this.$emit("getData");
                                this.handleClose(true);
                                return this.$message.success(res.msg)
                            }
                            this.$message.error(res.msg)
                        }).catch(res => {
                            console.log(res)
                        })
                    } else {
                        adviserSave.add(this.form).then(res => {
                            if(res.code == 1) {
                                this.$emit("getData");
                                this.handleClose();
                                return this.$message.success(res.msg)
                            }
                            this.$message.error(res.msg)
                        }).catch(res => {
                            console.log(res)
                        })
                    }
                } else {
                    this.$message.error("请检测必填、必选项！")
                    return false;
                }
            });
        },
	},
    beforeMount() {
        this.handleBrand(true);      // 获取厂品牌
    },
	watch: {
        "options.row": {
            handler: function(val, oldVal) {
                if (!val) {
                    // val = JSON.parse(JSON.stringify(this.formDefault))
                    val = {}
                } else {
                    if (val.brand1_id) {
                        this.handleBrand(true, val.brand1_id)
                    }
                }
                this.form = val
                this.visible = this.options.visible
            }
        }
    }
}
</script>
<style lang="scss" scoped>
.el-dialog__wrapper /deep/ {
    .el-dialog__body {
        padding: 20px 30px 0;
        z-index: 200;
    }
}
.el-form /deep/ {
    .el-form-item__label {
        line-height: 100%;
        padding-bottom: 10px;
        width: 100%;
        text-align: left;
    }
    .el-select, .el-input {
        width: 400px;
    }
}
</style>
